<?php
/**
 * Created by PhpStorm.
 * User: qufan
 * Date: 2016/12/17 0017
 * Time: 10:34
 */

namespace Home\Controller;


use Common\Logic\DatumDicLogic;
use Common\Logic\ExcelLogic;
use Think\Upload;

class DataController extends HomeController
{
    public function index(){
        $this->meta_title = '资料管理';
        $this->dicClasses = M('DatumDicClass')->select();
        $this->display();
    }

    /**
     * 资料导入json接口
     */
    public function import(){
        $flag = false;
        if(!empty($_FILES['file_import']['name'])){
            $upload = new Upload();
            $upload->exts = array('xls', 'xlsx');
            $upload->savePath = "temp/";
            $upload->saveRule = "time";
            $upload->subName = "";
            if (! $info = $upload->upload ( $_FILES )) {
                $this->error ( $upload->getError () );
            } else { // 上传成功 获叏上传文件信息
                $resurl = $upload->rootPath . $info ['file_import'] ['savepath'] . $info ['file_import'] ['savename'];
                $excelData = ExcelLogic::read($resurl);
                $class_id = $_POST['class_id'];
                ExcelLogic::importData($class_id, $excelData, $this->orgcode);

                //导入完毕删除上传的临时文件
                if (file_exists ( $resurl )) {
                    unlink ( $resurl );
                }
                $flag = true;
            }
        }
        if ($flag) {
            logOperation('资料管理','导入资料');
            $this->sucessJson();
        } else {
            $this->errorJson( '导入失败' );
        }
    }

    /**
     * 获得资料类别树json接口
     */
    public function getDatumTree(){
        $tree = DatumDicLogic::getDatumDicTree();
        if($tree){
            $this->sucessJson($tree);
        }else{
            $this->errorJson('获取资料类别信息失败');
        }
    }

    /**
     * 查询相关数据表字段信息
     * @param $datum_dic_class
     */
    public function getTableFields($datum_dic_class){
        $classToTable = C('CLASS_TO_TABLE');
        $tableName = $classToTable[$datum_dic_class]['name'];
        $fields = M($tableName)->getDbFields();
        $fields = getFieldsDescr($fields);
        if($classToTable[$datum_dic_class]['hasType']){
            $fields[] = array('field'=>'type_name','title'=>'类型');
        }

        foreach ($fields as &$field){
            if ($datum_dic_class == 6){
                if($field['field'] == 'level'){
                    $field = array('field'=>'type_name','title'=>'级别');
//                    break;
                }
//                $fields['level'] = array('field'=>'type_name', 'title'=>'级别');
            }
            if ($datum_dic_class == 10){
                if($field['field'] == 'classification'){
                    $field = array('field'=>'lawlevel_type_name','title'=>'分类');
//                    break;
                }
//                $fields['level'] = array('field'=>'type_name', 'title'=>'级别');
            }
            if ($datum_dic_class == 13){
                if($field['field'] == 'emResource_type_id'){
                    $field = array('field'=>'resource_name','title'=>'物质来源');
                }
                if ($field['field'] == 'place_id') {
                    $field = array('field'=>'place_id','title'=>'存储位置');
                }
            }
            if($field['field'] == 'administrative_division_code'){
                $field = array('field'=>'administrative_division_name','title'=>'行政区划');
//                break;
            }
        }
        if($fields){
            $this->sucessJson($fields);
        }else{
            $this->errorJson('没有字段信息');
        }
    }

    /**
     * 列表查询指定资料表的数据json接口
     * @param $limit
     * @param $offset
     * @param $datum_dic_class
     * @param $datum_dic_type
     * @param null $search
     */
    public function dataList($limit, $offset, $datum_dic_class, $datum_dic_type, $search=null){
        $classToTable = C('CLASS_TO_TABLE');
        if(isset($classToTable[$datum_dic_class])){
            $tableName = $classToTable[$datum_dic_class]['name'];
            $needAd = $classToTable[$datum_dic_class]['needAd'];
            $hasType = $classToTable[$datum_dic_class]['hasType'];

            if(!empty($this->uids)){
                $map['_string'] = "a.orgcode in(".implode(',', $this->codes).")";
            }
            $map['a.state'] = 1;


            empty($search) or $map['a.name'] = array('like', "%{$search}%");
            $field = 'a.* ';
            $model = M($tableName)->alias('a');
            if($datum_dic_class == 6){
                empty($datum_dic_type) or $map['level'] = $datum_dic_type;
                $field = $field . ', type_name';
                $model = $model->join('datum_dic_type ddt on a.level=ddt.type_code');
            }else{
                empty($datum_dic_type) or $map['type'] = $datum_dic_type;
            }
            if($datum_dic_class == 10){
                $field = $field . ', lawlevel_type_name';
                $model = $model->join('lawlevel_type lt on a.classification=lt.lawlevel_type_code');
            }
            if ($datum_dic_class == 13) {
                $field = $field . ', et.name as resource_name';
                $model = $model->join('emresource_type et on a.emResource_type_id=et.code');
            }
            if($hasType){
                $field = $field . ', type_name';
                $model = $model->join('datum_dic_type ddt on a.type=ddt.type_code');
            }
            if($needAd){
                $field = $field . ', administrative_division_name';
                $model = $model->join('administrative_division ad on a.administrative_division_code = ad.administrative_division_code', 'left');
            }
            $record = $model->field($field)->where($map)->limit($offset, $limit)->select();
            $total_count = $model->where($map)->count();
            if($datum_dic_class == 13)
                $record = $this->storePosition($record);
            $result['rows'] = $record;
            $result['total'] = $total_count;

        }else{
            $result['rows'] = array();
            $result['total'] = 0;
        }
        $this->ajaxReturn($result);
    }
    /** 
    *func: 物资与装备 存储位置获取
    *user: 边个懂
    *time: 20170519
    **/
    public function storePosition($rows){
        $storePosition = C('STORE_POSITION');
        if (is_array($rows)) {
            for ($i=0; $i < count($rows); $i++) { 
                if ($rows[$i]['resource_name'] == $storePosition[$rows[$i]['resource_name']]['name']) {
                    $t = $storePosition[$rows[$i]['resource_name']]['table'];
                    $r = M($t)->where(array($storePosition[$rows[$i]['resource_name']]['outer_key']=>$rows[$i]['place_id']))->find();
                    $rows[$i]['place_id'] = $r['name'];
                }
            }
            return $rows;
        }
    }
    /**
     * 查询资料附件数据json接口
     * @param $datum_dic_class
     * @param $datum_id
     */
    public function queryDatumEnclosure($datum_dic_class, $datum_id){
        $where['class_id'] = $datum_dic_class;
        $where['relation_id']= $datum_id;
        $record = M('DatumEnclosure')->where($where)->select();
        if($record){
            $this->sucessJson($record);
        }else{
            $this->errorJson('没有附件');
        }
    }

}